define([
    'js/resolve',
    'angular-ui-bootstrap'
], function(resolve) {
    angular.module('app.combobox', ['ui.bootstrap'])
        .directive('combobox', comboBoxDirective);

    function comboBoxDirective($timeout) {
        return resolve({
            restrict: 'E',
            replace: true,
            templateUrl: 'js/templates/combobox.html',
            require: '?ngModel',
            scope: {
                ngModel: '=',
                editable: '=',
                disabled: '<',
                required: '<',
                options: '<',
                onSelected: '<'
            },
            link: function(scope, element, attrs, ngModel) {
                scope.value = '';
                scope.label = '';
                scope.options = scope.options || [];
                if (ngModel) {
                    scope.value = scope.ngModel || '';
                    scope.$watch('value', function(newValue) {
                        ngModel.$setViewValue(newValue);
                    });
                }
                angular.forEach(scope.options, function(option) {
                    if (option['selected'] === true || option.value == scope.value) {
                        scope.value = option.value;
                        scope.label = option.label;
                        callSelectedCallback(scope.value);
                    }
                });
                //
                element.find('input').bind('keypress', function(event) {
                    if (event.keyCode == 13) {
                        callSelectedCallback(scope.value);
                    }
                });
                $timeout(function() {
                    element.find('.input-handler').bind('click', function(event) {
                        callSelectedCallback(scope.value);
                    });
                });
                //
                scope.select = function(option) {
                    scope.value = option.value;
                    scope.label = option.label;
                    angular.forEach(scope.options, function(_option) {
                        _option['selected'] = (_option == option ? true : false);
                    });
                    callSelectedCallback(scope.value);
                }
                //
                function callSelectedCallback(value) {
                    if (typeof(scope.onSelected) === 'function') {
                        var selection = null;
                        angular.forEach(scope.options, function(option) {
                            if (option.value == value) {
                                selection = option;
                            }
                        });
                        scope.onSelected(scope.value, selection);
                    }
                }
            }
        });
    }
});
